<template>
  <div class="app-container">
    <div class="content">
      <h3 style="margin-bottom: 30px">1.分校基本信息</h3>
      <jblForm :ref-name.sync="formRef" :form.sync="form" :value-data.sync="form.valueData">
        <template v-slot:form-logoImg>
          <el-upload
            class="avatar-uploader"
            action="#"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="businessLogo"
          >
            <img v-if="form.valueData.logoImg" :src="form.valueData.logoImg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>
        <template v-slot:form-doBusinessTime>
          <el-row v-for="(weekItem,index) in weekData" :key="index">
              <el-select style="width:100px" size="small" v-model="weekItem.weekStart" placeholder="请选择开始日期">
                <el-option
                  v-for="item in weekList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <span style="color:#606266">至</span>
              <el-select style="width:100px" size="small" v-model="weekItem.weekEnd" placeholder="请选择结束日期">
                <el-option
                  v-for="item in weekList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            <el-time-picker
              size="small"
              is-range
              v-model="weekItem.startEndTime"
              format="HH : mm"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
            <el-button v-show="index+1===weekData.length" size="small" icon="el-icon-plus" circle @click="addDoBusinessTime"></el-button>
            <el-button v-show="index+1!==weekData.length" size="small" icon="el-icon-minus" circle @click="romoveDoBusinessTime(index)"></el-button>
          </el-row>
        </template>
      </jblForm>

      <h3 style="margin:40px 0 30px">2.分校属性设置</h3>
      <jblForm
        :ref-name.sync="schoolFormFormRef"
        :form.sync="schoolForm"
        :value-data.sync="schoolForm.valueData"
      >
        <template v-slot:form-synopsisImg>
          <el-row type="flex">
            <draggable style="display:flex" v-model="schoolForm.valueData.synopsisImg"  :options = "{animation:500}">
            <div
              v-for="(item,index) in schoolForm.valueData.synopsisImg"
              :key="index"
              class="img-upload"
            >
              <div v-if="index===0" class="zt">主图</div>
              <img style="width:100%;height:100%" fit="contain" :src="item" />
              <div class="img-upload-shaow">
                <i class="el-icon-delete" @click="removeImg(index)" />
              </div>
            </div>
             </draggable>
            <!-- <div v-show="schoolForm.valueData.dialog" class="img-upload" @click="handleUpload">
              <i class="el-icon-plus" />
            </div>-->
            <el-upload
              class="avatar-uploader"
              action="#"
              :class="{disabled:avatarIsMax}"
              :show-file-list="false"
              :on-change="onAvatarChange"
              :http-request="handleUploda"
              :before-upload="beforeUpload"
              :on-exceed="onExceed"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-row>
        </template>
        <template v-slot:form-detail>
          <el-row>
            <el-select
              size="small"
              style="width:160px"
              v-model="schoolForm.province"
              placeholder="请选择省份"
              @change="provinceChange"
            >
              <el-option
                v-for="item in addressOptions.province"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              size="small"
              style="width:160px"
              v-model="schoolForm.city"
              placeholder="请选择城市"
              @change="cityChange"
            >
              <el-option
                v-for="item in addressOptions.city"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              size="small"
              style="width:160px"
              v-model="schoolForm.area"
              placeholder="请选择市区"
              @change="areaChange"
            >
              <el-option
                v-for="item in addressOptions.area"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              size="small"
              style="width:160px"
              v-model="schoolForm.street"
              placeholder="请选择街道( 可空 )"
              @change="streetChange"
            >
              <el-option
                v-for="item in addressOptions.street"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-row>
          <el-row>
            <el-input
              size="mini"
              style="width:390px"
              v-model="schoolForm.valueData.detail"
              placeholder="点击获取定位地址"
              @focus="openTmap"
            ></el-input>
          </el-row>
        </template>
        <template v-slot:form-categoryIds>
          <el-row>
            <el-checkbox v-model="schoolForm.valueData.checked">应用总校开设的分类</el-checkbox>
          </el-row>
          <el-row>
            <el-tabs v-model="activeName">
              <el-tab-pane
                v-for="item in categoryAllList"
                :key="item.id"
                :label="item.name"
                :name="item.id">
                  <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll[index]" @change="handleCheckAllChange">全选</el-checkbox> -->
                  <div style="margin: 15px 0;"></div>
                  <el-checkbox-group v-model="schoolForm.valueData.categoryIds">
                    <el-checkbox v-for="categories in item.categories" :label="categories.id" :key="categories.id">{{categories.name}}</el-checkbox>
                  </el-checkbox-group>
                </el-tab-pane>
            </el-tabs>
          </el-row>
        </template>
      </jblForm>

      <h3 style="margin:40px 0 30px">3.分校超级管理员配置</h3>
      <jblForm
        :ref-name.sync="superAdminFormRef"
        :form.sync="superAdminForm"
        :value-data.sync="superAdminForm.valueData"
      >
      <template v-slot:form-tip>
        <span style="color:#ccc">注意事项：如果负责人电话为已注册过的账号，则密码为原密码</span>
      </template>
      </jblForm>

      <el-row type="flex" justify="center">
        <el-button @click="closeEdit">取消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="toSubmit">保存</el-button>
      </el-row>
    </div>
    <el-dialog
      title="选择地址"
      :visible.sync="addressOptions.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @opened="addressDialog"
      @close="1"
      width="750px"
    >
      <div ref="mapArry" style="width:100%;height:600px">
        <iframe
          id="mapPage"
          width="100%"
          height="100%"
          frameborder="0"
          src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY&referer=myapp"
        ></iframe>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressOptions.dialog = false">取 消</el-button>
        <el-button type="primary" @click="addressOptions.dialog = false">关闭</el-button>
      </div>
    </el-dialog>
  <!-- 图片裁剪 -->
     <el-dialog
        title="裁剪图片"
        :visible.sync="cropper.dialog"
        width="800px"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        @open="cropperOpen"
        @closed="cropperClose"
        >
        <div class="vue-cropper" :style="{'width':cropper.width,'height':cropper.height}">
          <VueCropper
              ref="cropper"
              :img="option.img"
              :outputSize="option.size"
              :outputType="option.outputType"
              :info="true"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :fixed="option.fixed"
              :fixedNumber="option.fixedNumber"
              :centerBox="option.centerBox"
              :infoTrue="option.infoTrue"
              :fixedBox="option.fixedBox"
            ></VueCropper>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cropper.dialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import jblForm from '@/components/JblForm'
import cropper from '@/components/cropper'
import { VueCropper } from 'vue-cropper'
import draggable from 'vuedraggable'

import {
  provinceList,
  cityList,
  areaList,
  streetList,
  getCategoryAll
} from '@/api/common'
import {
  merchantType,
  getAllLabels,
  getById
} from '@/api/mechanism'

export default {
  name: 'EditForm',
  components: {
    jblForm,
    cropper,
    VueCropper,
    draggable
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      avatarIsMax: false,
      submitLoading: false,
      formRef: {},
      schoolFormFormRef: {},
      superAdminFormRef: {},
      isLogoImg: true,
      // 裁剪组件的基础配置option
      option: {
        mode: 'cover', // 图片默认渲染方式
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 750, // 默认生成截图框宽度
        autoCropHeight: 560, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [750, 560], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      cropper: {
        dialog: false,
        src: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg',
        width: '750px',
        height: '560px',
        aspectRatio: 1,
        fileBlob: {}
      },
      activeName: '1',
      categoryAllList: [], // 所有分类集合
      checkAll: [],
      isIndeterminate: true,
      checkedCities: [],
      categorySonItem: [], // 子分类
      weekData: [
        {
          weekStart: null,
          weekEnd: null,
          startEndTime: null
        }
      ],
      weekList: [
        {
          value: 1,
          label: '每周一'
        },
        {
          value: 2,
          label: '每周二'
        },
        {
          value: 3,
          label: '每周三'
        },
        {
          value: 4,
          label: '每周四'
        },
        {
          value: 5,
          label: '每周五'
        },
        {
          value: 6,
          label: '每周六'
        },
        {
          value: 0,
          label: '每周日'
        }
      ],
      form: {
        file: {},
        data: [
          {
            type: 'slot',
            prop: 'logoImg',
            required: true,
            labelWidth: '120px',
            show: () => {},
            label: '机构logo',
            rules: [
              { required: true, message: '请上传机构logo', trigger: 'blur' }
            ]
          },
          {
            type: 'input',
            labelWidth: '120px',
            prop: 'name',
            label: '机构名称',
            placeholder: '请输入机构名称',
            rules: [
              { required: true, message: '请输入机构名称', trigger: 'blur' },
              {
                min: 1,
                max: 40,
                message: '长度在 1 到 40 个字符',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'ymdDatetime',
            valueFormat: 'timestamp',
            labelWidth: '120px',
            prop: 'foundTime',
            label: '开业日期',
            placeholder: '请填写开业日期',
            // rules: [
            //   {
            //     // required: true,
            //     message: '请选择时间',
            //     trigger: 'blur'
            //   }
            // ]
          },
          {
            type: 'slot',
            prop: 'doBusinessTime',
            show: () => {},
            labelWidth: '120px',
            label: '营业时间'
          },
          {
            type: 'inputNumber',
            labelWidth: '120px',
            prop: 'serverPhone',
            label: '服务电话',
            placeholder: '请输入机构服务电话',
            rules: [
              { required: true, validator: validatePhone, trigger: 'blur' },
            ]
          },
          {
            type: 'tinymce',
            labelWidth: '120px',
            height: 400,
            prop: 'synopsis',
            label: '机构简介',
            placeholder: '请填写机构简介',
            rules: [
              {
                required: true,
                message: '请填写机构简介',
                trigger: 'blur'
              }
            ]
          }
        ],
        valueData: {
          src: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg',
          logoImg: '',
          detail: ''
        }
      },
      isMax: false,
      schoolForm: {
        dialog: false,
        topTypeIndex: '0',
        allTypeList: [],
        topTypeList: [],
        childrenType: [],
        chooseTypes: [],
        checkTypeAll: false,
        isTypeIndeterminate: true,
        AllLabels: [],
        province: '', // 省
        city: '',
        area: '',
        street: '',
        data: [
          {
            type: 'slot',
            prop: 'synopsisImg',

            show: () => {},
            labelWidth: '140px',
            label: '机构轮播宣传图',
            rules: [
              { required: true, message: '请上传机构宣传图', trigger: 'blur' }
            ]
          },
          {
            type: 'slot',
            prop: 'detail',
            show: () => {},
            labelWidth: '140px',
            label: '定位地址',
            rules: [
              { required: true, message: '地址不能为空', trigger: 'blur' }
            ]
          },
          {
            type: 'input',
            labelWidth: '140px',
            prop: 'addressRemarks',
            label: '详细地址',
            placeholder: '请输入详细地址',
            rules: [
              { required: true, message: '请输入详细地址', trigger: 'blur' }
            ]
          },
          {
            type: 'slot',
            prop: 'categoryIds',
            show: () => {},
            labelWidth: '140px',
            label: '课程开设分类',
            rules: [
              { required: true, message: '课程开设分类', trigger: 'change' }
            ]
          },
          {
            type: 'checkboxGroup',
            labelWidth: '140px',
            prop: 'labels',
            label: '标签选择',
            checkboxGroup: () => {
              return this.schoolForm.AllLabels
            },
            rules: [
              { required: true, message: '请选择标签', trigger: 'change' }
            ]
          }
        ],
        valueData: {
          imageUrl: '',
          detail: '',
          latLng: '',
          categoryIds: [],
          categoryNames: [],
          addressValue: '',
          province: '', // 省
          city: '', // 市
          region: '', // 区
          town: '', // 街道
          lat: '',
          lng: '',
          addressRemarks: '',
          checked: false,
          activeName: 'first',
          labels: [],
          synopsisImg: [
            // 'https://user-gold-cdn.xitu.io/2020/6/16/172ba7d1df3f69ab?imageView2/0/w/1280/h/960/format/webp/ignore-error/1'
          ]
        }
      },
      addressOptions: {
        dialog: false,
        province: [], // 省
        city: [],
        area: [],
        street: [],
        searchAdress: '',
        options: [],
        lat: '',
        lng: '',
        currentCity: ''
      },
      superAdminForm: {
        data: [
          {
            type: 'input',
            labelWidth: '125px',
            prop: 'principalName',
            label: '校长（负责人）',
            placeholder: '请输入姓名',
            rules: [
              { required: true, message: '请输入姓名', trigger: 'blur' }
            ]
          },
          {
            type: 'inputNumber',
            labelWidth: '125px',
            prop: 'principalPhone',
            label: '负责人电话',
            placeholder: '请输入负责人电话',
            rules: [
              {
                required: true,
                message: '请输入负责人电话',
                trigger: 'blur'
              },
              { validator: validatePhone, trigger: 'change' }
            ]
          },
          {
            type: 'input',
            disabled: true,
            labelWidth: '125px',
            prop: 'serverPhone',
            label: '登录账号',
            placeholder: '登录账号为负责人电话'
          },
          {
            type: 'input',
            disabled: true,
            labelWidth: '125px',
            prop: 'password',
            label: '初始密码',
            placeholder: '请输入密码'
          },
          {
            type: 'slot',
            prop: 'tip',
            labelWidth: '50px',
            show: () => {}
          }
        ],
        valueData: {
          password: 'JBL123456'
        }
      }
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  watch: {
    'schoolForm.valueData.synopsisImg'(val) {
      this.avatarIsMax = val.length >= 6
    },
    'schoolForm.valueData.checked'(v) {
      if (v) {
        getById({
          businessId: this.$store.getters.businessId
        }).then(res => {
          const data = res.data
          this.schoolForm.valueData.categoryIds = data.categoryIds.split(',')
        })
      } else {
        this.schoolForm.valueData.categoryIds = []
      }
    }
  },
  created() {
    this.getData()
    // this.refreshTopType()
  },
  mounted() {
    const that = this
    // 为了防止火狐浏览器拖拽的时候以新标签打开
    document.body.ondrop = function(event) {
      event.preventDefault()
      event.stopPropagation()
    }
    window.addEventListener(
      'message',
      function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module == 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          // console.log('location', loc)
          that.schoolForm.valueData.lat = loc.latlng.lat
          that.schoolForm.valueData.lng = loc.latlng.lng
          that.schoolForm.valueData.detail = `${loc.poiaddress}${loc.poiname}`
        }
      },
      false
    )
    this.getLocation()
  },
  methods: {
    addDoBusinessTime() {
      this.weekData.push(
        {
          weekStart: 1,
          weekEnd: 1,
          startEndTime: null
        }
      )
    },
    romoveDoBusinessTime(index) {
      this.weekData.splice(index, 1)
    },
    businessLogo(res, fileList) {
      this.isLogoImg = true
      this.cropper = {
        dialog: true,
        src: '',
        width: '400px',
        height: '400px'
      }
      this.option.fixedNumber = [1, 1]
      // this.cropper.src = URL.createObjectURL(res.file)
      this.option.img = URL.createObjectURL(res.file)
    },
    cropperOpen(url) {
      // this.cropper.src = url
    },
    // 裁剪后上传
    fileBlob(blod) {
      const raw = {
        raw: blod,
        name: new Date().valueOf()
      }
      this.uploadImgToOss(raw).then(response => {
        const { imgUrl } = response
        if (this.isLogoImg) {
          this.form.valueData.logoImg = imgUrl
        } else {
          this.schoolForm.valueData.synopsisImg.push(imgUrl)
        }
      }).finally(() => {
        this.cropper.dialog = false
      })
    },
    cropperClose() {
      // this.cropper.src = ''
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file, 'res, file')
      // this.form.valueData.imageUrl = URL.createObjectURL(file.raw)
      // this.form.valueData.imageUrl = file.raw
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    onExceed() {
      this.$message({
        message: '最多上传6张图片',
        type: 'warning'
      })
    },
    handleUploda(res, fileList) {
      this.isLogoImg = false
      this.cropper = {
        dialog: true,
        src: '',
        width: '750px',
        height: '560px'
      }
      this.option.fixedNumber = [750, 560]
      // this.cropper.src = URL.createObjectURL(res.file)
      this.option.img = URL.createObjectURL(res.file)
    },
    onAvatarChange(file, fileList) {
      this.avatarIsMax = fileList.length >= 6
    },
    // 确定裁剪
    confirmCropper() {
      this.$refs.cropper.getCropBlob((data) => {
        // var fileName = 'goods' + this.fileinfo.uid
        const raw = {
          raw: data,
          name: new Date().valueOf()
        }
        this.uploadImgToOss(raw)
          .then(response => {
            const { imgUrl } = response
            if (this.isLogoImg) {
              this.form.valueData.logoImg = imgUrl
            } else {
              this.schoolForm.valueData.synopsisImg.push(imgUrl)
            }
          })
          .finally(() => {
            this.cropper.dialog = false
          })
      })
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 删除相册图片
    removeImg(index) {
      this.schoolForm.valueData.synopsisImg.splice(index, 1)
    },
    async openTmap(v) {
      this.addressOptions.dialog = true
    },
    // 省
    provinceChange(v) {
      this.schoolForm.valueData.province = this.addressOptions.province.find(i => i.value === this.schoolForm.province).label
      this.schoolForm.city = null
      this.schoolForm.area = null
      this.schoolForm.street = null
      cityList({
        pid: v
      }).then(res => {
        this.addressOptions.city = res.data.map(i => {
          return {
            label: i.cityName,
            value: i.cityCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    // 市
    cityChange(v) {
      this.schoolForm.valueData.city = this.addressOptions.city.find(i => i.value === this.schoolForm.city).label
      this.schoolForm.area = null
      this.schoolForm.street = null
      areaList({
        pid: v
      }).then(res => {
        this.addressOptions.area = res.data.map(i => {
          return {
            label: i.areaName,
            value: i.areaCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    // 区
    areaChange(v) {
      this.schoolForm.valueData.region = this.addressOptions.area.find(i => i.value === this.schoolForm.area).label
      this.schoolForm.street = null
      streetList({
        pid: v
      }).then(res => {
        this.addressOptions.street = res.data.map(i => {
          return {
            label: i.streetName,
            value: i.streetCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
      const province = this.schoolForm.valueData.province
      const city = this.schoolForm.valueData.city
      const area = this.schoolForm.valueData.region
      console.log(`${province}${city}${area}`)
      this.schoolForm.valueData.addressRemarks = `${province}${city}${area}`
    },
    // 街道
    streetChange(v) {
      this.schoolForm.valueData.town = this.addressOptions.street.find(i => i.value === this.schoolForm.street).label
      const province = this.schoolForm.valueData.province
      const city = this.schoolForm.valueData.city
      const area = this.schoolForm.valueData.region
      const street = this.schoolForm.valueData.town
      // console.log(`${province}${city}${area}`)
      this.schoolForm.valueData.addressRemarks = `${province}${city}${area}${street}`
    },
    getData() {
      provinceList().then(res => {
        this.addressOptions.province = res.data.map(i => {
          return {
            label: i.provinceName,
            value: i.provinceCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
      getAllLabels({
        status: 1,
        type: null
      }).then(res => {
        const data = res.data
        data.forEach(i => {
          i.label = i.name
          i.value = i.id
        })
        this.schoolForm.AllLabels = data
      })
      // 获取课程分类
      getCategoryAll().then(res => {
        this.categoryAllList = res.data
      })
    },
    addressDialog() {
      // this.initMap()
    },
    // 获取定位
    async getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(this.showPosition)
      } else {
        this.$message({
          message: '获取不到你的位置信息',
          type: 'warning'
        })
      }
      const options = { timeout: 1000 }
      const geolocation = new qq.maps.Geolocation(
        'R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY',
        'myapp'
      )
      geolocation.getLocation(
        position => {
          this.addressOptions.lat = position.lat
          this.addressOptions.lng = position.lng
        }, err => {
          // console.log(err, '获取定位失败，重新获取中...')
          this.getLocation()
        },
        options
      )
    },
    showPosition(position) {
      console.log(position, 'opopoppop')
    },

    toSubmit() {
      this.fnThrottle(this.submit, 1000, 1000)()
    },
    submit() {
      // this.schoolForm.valueData.labels = this.schoolForm.valueData.labels.join(',')
      let form1 = false
      let form2 = false
      let form3 = false
      this.formRef.validate((valid) => {
        if (valid) {
          form1 = true
        } else {
          return false
        }
      })
      this.schoolFormFormRef.validate((valid) => {
        if (valid) {
          form2 = true
        } else {
          return false
        }
      })
      this.superAdminFormRef.validate((valid) => {
        if (valid) {
          form3 = true
        } else {
          return false
        }
      })
      if (!(form1 && form2 && form3)) {
        return this.$message.error('请完善学校信息')
      }
      // 所有子分类
      const categoryArr = []
      this.categoryAllList.forEach(i => {
        categoryArr.push(...i.categories)
      })
      // 选中的子分类对象
      const same = categoryArr.filter(i => {
        return this.schoolForm.valueData.categoryIds.indexOf(i.id) !== -1
      })
      // 选中的子分类name
      const categoryNames = same.map(i => {
        return i.name
      })
      // 选中的父分类id
      const parentIds = same.map(i => {
        return i.parentId
      })
      const categoryParentIds = Array.from(new Set(parentIds))
      const categoryParentNames = []
      const classify = []
      // 选中的父分类对象集合
      const parentObj = this.categoryAllList.filter(i => {
        return categoryParentIds.indexOf(i.id) !== -1
      })
      parentObj.forEach(i => {
        categoryParentNames.push(i.name)
        classify.push(i.classify)
      })
      let type = null
      const classifytype = [...new Set(classify)]
      const p = classifytype.reduce((prev, curr) => {
        return prev + curr
      })
      switch (p) {
        case 1:
          type = 1
          break
        case 2:
          type = 2
          break
        case 3:
          type = 3
          break
      }
      const province = this.schoolForm.province
      const city = this.schoolForm.city
      const area = this.schoolForm.area
      const street = this.schoolForm.street
      const lat = this.schoolForm.valueData.lat
      const lng = this.schoolForm.valueData.lng
      if (!(province && city && area && lat && lng)) {
        return this.$message.error('请选择地址')
      }
      this.submitLoading = true
      const data = Object.assign({},
        this.form.valueData,
        this.schoolForm.valueData,
        this.superAdminForm.valueData
      )
      data.doBusinessTime = JSON.stringify(this.weekData)
      data.type = type
      data.addressIds = `${province},${city},${area},${street || ''}`
      data.categoryParentIds = categoryParentIds.join(',')
      data.categoryParentNames = categoryParentNames.join(',')
      data.categoryIds = data.categoryIds.join(',')
      data.categoryNames = categoryNames.join(',')
      data.synopsisImg = data.synopsisImg.join()
      data.labels = data.labels.join()
      this.$emit('submit', data)
      this.submitLoading = false
    },
    closeEdit() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push('/mechanism/school/list')
      // const tagsAll = this.$store.state.tagsView.visitedViews
      // const tag = tagsAll.find(i => i.path === '/mechanism/edit')
      // this.$store.dispatch('tagsView/delView', tag).then(({ visitedViews }) => {
      //   this.$router.replace({ path: '/redirect/mechanism/list' })
      // })
    },
    // 节流
    fnThrottle(method, delay, duration) {
      var that = this
      var timer = this.timer
      var begin = new Date().getTime()
      return function() {
        var context = that
        var args = arguments
        var current = new Date().getTime()
        clearTimeout(timer)
        if (current - begin >= duration) {
          method.apply(context, args)
          begin = current
        } else {
          // console.log(delay)
          that.timer = setTimeout(function() {
            method.apply(context, args)
          }, delay)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  width: 100%;
}
.img-upload {
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 5px;
  width: 187.5px;
  height: 140px;
  border: 1px dashed #6bb6fc;
  border-radius: 5px;
  .zt {
    z-index: 2;
    position: absolute;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 30px;
    color: #fff;
    background: rgba(0, 0, 0, 0.7);
  }
  i {
    font-size: 24px;
    color: #6bb6fc;
  }
  .el-image {
    cursor: pointer;
    width: 100%;
    height: 100%;
  }
  &:hover .img-upload-shaow {
    display: flex;
  }
  .img-upload-shaow {
    display: none;
    // display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    background: rgba(0, 0, 0, 0.3);
    // opacity: 0;
    > i {
      color: #fff;
    }
  }
}
/deep/.el-input--medium .el-input__inner{
  width: 40%;
}
/deep/.el-date-editor.el-input, .el-date-editor.el-input__inner{
  .el-input__inner{
    width: 220px;
  }
}
.disabled /deep/.el-upload--picture-card {
  display: none;
}
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
/deep/.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.searchAdress {
  margin-bottom: 10px;
  .el-select-dropdown__item {
    height: 70px;
  }
}
.disabled /deep/.el-upload{
    display: none
}
// 截图
.vue-cropper {
    width: 100%;
    text-align:center;
}
</style>
